package com.example.testjenkins.juc;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.IntStream;

public class CompletableFutureTest2 {
    public static void main(String[] args) {
        long l1 = System.currentTimeMillis();

        List<CompletableFuture<Integer>> futureList = Arrays.asList(
                getIntegerCompletableFuture("------come in 1 ------", 10),
                getIntegerCompletableFuture("------come in 2 ------", 20),
                getIntegerCompletableFuture("------come in 4 ------", 30)
        );
        System.out.println(futureList.stream().flatMapToInt(item -> IntStream.of(item.join())).sum());

        System.out.println(System.currentTimeMillis() - l1);
    }

    private static CompletableFuture<Integer> getIntegerCompletableFuture(String out, int num) {
        return CompletableFuture.supplyAsync(() -> {
                    System.out.println(Thread.currentThread().getName() + out);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return num;
                }
        );
    }

    private static void test1() {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("------come in 1 ------");
            return 10;
        }).thenCombine(CompletableFuture.supplyAsync(() -> {
            System.out.println("------come in 2 ------");
            return 20;
        }), (x, y) -> {
            System.out.println("------come in 3 ------");
            return x + y;
        }).thenCombine(CompletableFuture.supplyAsync(() -> {
            System.out.println("------come in 4 ------");
            return 30;
        }), (x, y) -> {
            System.out.println("------come in 5 ------");
            return x + y;
        });

        System.out.println("------result：" + completableFuture.join());
    }
}
